﻿#include "SshAdapter.h"
#include <QtConcurrent>
#include"kits/Config.h"

//执行linux命令
static void asynRunCmd(int channelNo, QString szData,void* obj){
    SshAdapter *sshAdapter =  (SshAdapter*)obj;
    sshAdapter->getSshManger()->write(channelNo,szData.toLatin1().data());
    sshAdapter->cmdResult(sshAdapter->getSshManger()->read(channelNo).c_str());
}

//登录linux系统
static void asynRunLogin(QString ipAddr,QString userName,QString password,void* obj){
    SshAdapter *sshAdapter =  (SshAdapter*)obj;
    if(!sshAdapter->getSshManger()->connect(ipAddr.toStdString().c_str())){
        sshAdapter->loginResult(false);
        return;
    }
    if (!sshAdapter->getSshManger()->login(userName.toLatin1().data(), password.toLatin1().data())){
        sshAdapter->loginResult(false);
        return;
    }
    sshAdapter->loginResult(true);

}

SshAdapter::SshAdapter(QObject* parent):QObject(parent)
{
    mSshManger = new QSshManager(this);
}

//异步登录
void SshAdapter::login(const QString &ipAddr, const QString &username, const QString &password)
{

    QtConcurrent::run(asynRunLogin,ipAddr,username,password,(void*)this);
}
//例如开启某个服务 cmd=service mysqld start
//异步执行命令
void SshAdapter::runCmd(const QString &cmd)
{
   QtConcurrent::run(asynRunCmd,channelNo,cmd,(void*)this);

}

void SshAdapter::cmdResult(const char *data)
{
    xPrint<<data;
}

void SshAdapter::loginResult(bool result)
{
    xPrint<<"login result:"<<result;
    if(!result) return;

    channelNo = mSshManger->createChannel("centos");
     if (channelNo == -1) {
        xPrint<<"Create Channel Failed ";
     }
}

QSshManager *SshAdapter::getSshManger() const
{
    return mSshManger;
}
